/**
 * 用户服务
 */

const Logger = require('../utils/logger')
const Validator = require('../utils/validator')
const Generator = require('../utils/generator')
const config = require('../config/config')

class UserService {
  constructor(userRepo) {
    this.userRepo = userRepo
  }

  /**
   * 创建新用户
   */
  async createUser(userData) {
    Logger.info('UserService', '创建新用户', { 
      username: userData.username, 
      phone: userData.phone 
    })

    // 参数验证
    if (userData.username) {
      Validator.validateUsername(userData.username)
    }
    if (userData.phone) {
      Validator.validatePhone(userData.phone)
    }
    if (userData.password) {
      Validator.validatePassword(userData.password)
    }
    if (userData.email) {
      Validator.validateEmail(userData.email)
    }

    // 检查用户名是否存在
    if (userData.username) {
      const existingUser = await this.userRepo.findByUsername(userData.username)
      if (existingUser) {
        throw new Error('用户名已存在')
      }
    }

    // 检查手机号是否存在
    if (userData.phone) {
      const existingPhone = await this.userRepo.findByPhone(userData.phone)
      if (existingPhone) {
        throw new Error('手机号已被注册')
      }
    }

    // 检查邮箱是否存在
    if (userData.email) {
      const existingEmail = await this.userRepo.findByEmail(userData.email)
      if (existingEmail) {
        throw new Error('邮箱已被注册')
      }
    }

    // 设置默认值
    const newUser = {
      username: userData.username || userData.phone,
      password: userData.password,
      phone: userData.phone || '',
      email: userData.email || '',
      nickname: userData.nickname || userData.username || `用户${userData.phone ? userData.phone.slice(-4) : ''}`,
      avatar: userData.avatar || Generator.randomAvatar(),
      role: config.user.defaultRole,
      level: config.user.defaultLevel,
      permissions: [],
      status: 'active',
      openid: userData.openid || '',
      hasDefaultPassword: userData.hasDefaultPassword || false,
      points: config.user.defaultPoints,
      createTime: new Date()
    }

    // 创建用户
    const userId = await this.userRepo.create(newUser)

    Logger.info('UserService', '用户创建成功', { userId })

    return { userId, userInfo: { ...newUser, _id: userId } }
  }

  /**
   * 更新用户最后登录时间和openid
   */
  async updateLoginInfo(userId, openid) {
    const updateData = {
      lastLoginTime: new Date()
    }
    if (openid) {
      updateData.openid = openid
    }
    await this.userRepo.update(userId, updateData)
  }

  /**
   * 格式化用户信息（删除敏感字段）
   */
  formatUserInfo(user) {
    const userInfo = {
      id: user._id,
      username: user.username,
      nickname: user.nickname || user.username || `用户${user.phone ? user.phone.slice(-4) : ''}`,
      name: user.nickname || user.username || `用户${user.phone ? user.phone.slice(-4) : ''}`,
      phone: user.phone,
      email: user.email,
      avatar: user.avatar || '',
      role: user.role || config.user.defaultRole,
      level: user.level || config.user.defaultLevel,
      permissions: user.permissions || [],
      hasDefaultPassword: user.hasDefaultPassword || false,
      status: user.status || 'active',
      createTime: user.createTime,
      lastLoginTime: user.lastLoginTime || new Date(),
      loginTime: new Date().toISOString(),
      points: user.points || 0
    }
    return userInfo
  }
}

module.exports = UserService

